package com.earthea.chatbot.common.validator;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class PasswordValidatorImpl implements ConstraintValidator<PasswordValidator, String> {
    private static final String SPECIAL_CHARS = "!@#$%^&*()_+-=[]{}|;:',.<>?/";

    @Override
    public boolean isValid(String password, ConstraintValidatorContext context) {
        return isValid(password);
    }

    public static boolean isValid(String password) {
        if (StringUtils.isBlank(password)) {
            return false;
        }

        boolean hasUpper = false;
        boolean hasLower = false;
        boolean hasNumber = false;
        boolean hasSpecial = false;

        for (char c : password.toCharArray()) {
            if (Character.isUpperCase(c)) {
                hasUpper = true;
            } else if (Character.isLowerCase(c)) {
                hasLower = true;
            } else if (Character.isDigit(c)) {
                hasNumber = true;
            } else if (SPECIAL_CHARS.indexOf(c) != -1) {
                hasSpecial = true;
            }
        }

        return hasUpper && hasLower && hasNumber && hasSpecial;
    }
}
